package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protocol;

    private Map<String,String> headers = new HashMap<String, String>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        /**
         * 调用解析请求行
         */
        parseRequestLine();
        /**
         * 调用解析消息头
         */
        parseHeaders();
        /**
         * 调用解析消息正文
         */
        parseContent();

    }
    /**
     * 解析请求行
     */
    private void parseRequestLine() throws IOException {
        String line = readline();
        System.out.println("请求行内容:"+line);

        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    /**
     * 解析请求头
     */
    private void parseHeaders() throws IOException {
        while (true){
            String line = readline();
            if (line.isEmpty()){
                break;
            }
            String[] data = line.split(":\\s");
            headers.put(data[0],data[1]);
            System.out.println("消息头："+line);
        }
        System.out.println("headers:"+headers);
    }

    /**
     * 解析消息正文
     */
    private void parseContent(){

    }

    public String readline() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char cur = 'a';
        char pre = 'a';
        while ((d = in.read()) != -1) {
            cur = (char) d;
            if (cur == 10 && pre == 13) {
                break;
            }
            builder.append(cur);
            pre = cur;

        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
}
